package com.winz.cultureapp.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by admin on 2015/8/12.
 */
public class FileUtil {

    // 缓存根目录
    public static final String CACHE_BASE_PATH = Environment.getExternalStorageDirectory()
            + "/pb";

    /** 用户头像的缓存 **/
    public static final String URI_HEAD_PORTRAIT = CACHE_BASE_PATH + "/HEAD_PORTRAIT";
    /** 图片的缓存路径 **/
    public static final String URI_PIC = CACHE_BASE_PATH + "/PIC";
    public static final String URI_FILE= CACHE_BASE_PATH + "/FILE";

    /**
     * 检测缓存文件夹
     * @return
     */
    public static boolean checkCacheFolder() {
        File file = new File(URI_PIC);
        if (!file.exists()) {
            return file.mkdirs();
        }
        return true;
    }

    /**
     * 检测缓存文件夹
     * @return
     */
    public static boolean checkFileCacheFolder() {
        File file = new File(URI_FILE);
        if (!file.exists()) {
            return file.mkdirs();
        }
        return true;
    }


    /**
     * 方法一：
     * 从文件路径中获取文件名的方法
     * e.g. <br>
     * 举例：String fName ="G:\\Java_Source\\navigation_tigra_menu\\demo1\\img\\lev1_arrow.gif ";
     *
     * @param fileName
     * @return
     */
    public static String getFileName(String fileName) {
        File tempFile = new File(fileName.trim());
        return tempFile.getName();
    }
    public static String getFromAssets(Context context, String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 从文件路径中获取文件名的方法
     *
     * @param filename
     * @return
     */
    /*public static String getFileName(String filename) {
        String fName = filename.trim();
        String fileName = fName.substring(fName.lastIndexOf("/") + 1);
        //或者
        //String fileName = fName.substring(fName.lastIndexOf("\\") + 1);
        return fileName;
    }*/
    public static String getPrefix(String filename) {
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        return prefix;
    }

    /**
     * 判断是不是图片
     */
    public static boolean isImage(String url) {
        String filename = getFileName(url);
        String prefix = getPrefix(filename);
        if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg")
                || prefix.equalsIgnoreCase("bmp") || prefix.equalsIgnoreCase("gif")) {
            return true;
        }
        return false;
    }

    /**
     * 根据后缀名判断是不是图片
     *
     * @param postfix
     * @return
     */
    public static boolean isPostfixImage(String postfix) {
        if (postfix == null || postfix.equals("")) {
            return false;
        }
        if (postfix.equalsIgnoreCase("jpg") || postfix.equalsIgnoreCase("png") || postfix.equalsIgnoreCase("jpeg")
                || postfix.equalsIgnoreCase("bmp") || postfix.equalsIgnoreCase("gif")) {
            return true;
        }
        return false;
    }

    public static boolean isGIF(String url) {
        String filename = getFileName(url);
        String prefix = getPrefix(filename);
        if (prefix.equalsIgnoreCase("gif")) {
            return true;
        }
        return false;
    }

    /**
     * 判断是不是視頻
     *
     * @param url 视频支持：*.mp4;*.avi;*.mkv;*.wmv;*.asf;*.mov;*.3gp;*.flv;*.mpg;*.mpeg;*.mp3;
     */
    public static boolean isVedio(String url) {
        String filename = getFileName(url);
        String prefix = getPrefix(filename);
        if (prefix.equalsIgnoreCase("mp4") || prefix.equalsIgnoreCase("avi") || prefix.equalsIgnoreCase("mkv")
                || prefix.equalsIgnoreCase("wmv") || prefix.equalsIgnoreCase("asf") || prefix.equalsIgnoreCase("mov")
                || prefix.equalsIgnoreCase("3gp") || prefix.equalsIgnoreCase("flv") || prefix.equalsIgnoreCase("mpg")
                || prefix.equalsIgnoreCase("mpeg") || prefix.equalsIgnoreCase("mp3")) {
            return true;
        }
        return false;
    }


    public static File updateDir = null;
    public static File updateFile = null;
    /***********
     * 保存升级APK的目录
     ***********/
    public static final String KonkaApplication = "konkaUpdateApplication";

    public static boolean isCreateFileSucess;


    /**
     * 方法描述：createFile方法
     *
     * @param app_name
     * @return
     * @see FileUtil
     */
    public static void createFile(String app_name) {

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            isCreateFileSucess = true;

            updateDir = new File(Environment.getExternalStorageDirectory() + "/" + KonkaApplication + "/");
            updateFile = new File(updateDir + "/" + app_name + ".apk");

            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
            if (!updateFile.exists()) {
                try {
                    updateFile.createNewFile();
                } catch (IOException e) {
                    isCreateFileSucess = false;
                    e.printStackTrace();
                }
            }

        } else {
            isCreateFileSucess = false;
        }
    }

    /**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    public static boolean isPostfixMp3(String postfix) {
        if (postfix == null || postfix.equals("")) {
            return false;
        }
        if (postfix.equalsIgnoreCase("mp3") || postfix.equalsIgnoreCase("cda")
                || postfix.equalsIgnoreCase("cda") || postfix.equalsIgnoreCase("wav")
                || postfix.equalsIgnoreCase("aif") || postfix.equalsIgnoreCase("wma")
                || postfix.equalsIgnoreCase("ra") || postfix.equalsIgnoreCase("ram")
                || postfix.equalsIgnoreCase("midi") || postfix.equalsIgnoreCase("mid")
                || postfix.equalsIgnoreCase("mmf") || postfix.equalsIgnoreCase("amr")
                || postfix.equalsIgnoreCase("flac") || postfix.equalsIgnoreCase("aac")
                || postfix.equalsIgnoreCase("mod") || postfix.equalsIgnoreCase("au")) {
            return true;
        }
        return false;
    }



    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    // -----------------------7.0及以上版本 uri 解析获取文件真实路径------------------------------
    public static File getFileFromUri(Uri uri, Context context) {
        if (uri == null) {
            return null;
        }
        switch (uri.getScheme()) {
            case "content":
                return getFileFromContentUri(uri, context);
            case "file":
                return new File(uri.getPath());
            default:
                return null;
        }
    }
    /**
     * Gets the corresponding path to a file from the given content:// URI
     *
     * @param contentUri The content:// URI to find the file path from
     * @param context    Context
     * @return the file path as a string
     */

    private static File getFileFromContentUri(Uri contentUri, Context context) {
        if (contentUri == null) {
            return null;
        }
        File file = null;
        String filePath;
        String fileName;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, filePathColumn, null,
                null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
            fileName = cursor.getString(cursor.getColumnIndex(filePathColumn[1]));
            cursor.close();
            if (!TextUtils.isEmpty(filePath)) {
                file = new File(filePath);
            }
            if (TextUtils.isEmpty(filePath) || !file.exists() || file.length() <= 0) {
                filePath = getPathFromInputStreamUri(context, contentUri, fileName);
            }
            if (!TextUtils.isEmpty(filePath)) {
                file = new File(filePath);
            }
        }
        return file;
    }

    /**
     * 用流拷贝文件一份到自己APP目录下
     *
     * @param context
     * @param uri
     * @param fileName
     * @return
     */
    public static String getPathFromInputStreamUri(Context context, Uri uri, String fileName) {
        InputStream inputStream = null;
        String filePath = null;

        if (uri.getAuthority() != null) {
            try {
                inputStream = context.getContentResolver().openInputStream(uri);
                File file = createTemporalFileFrom(context, inputStream, fileName);
                filePath = file.getPath();

            } catch (Exception e) {
                Logger.e(e.getMessage());
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (Exception e) {
                    Logger.e(e.getMessage());
                }
            }
        }

        return filePath;
    }

    private static File createTemporalFileFrom(Context context, InputStream inputStream, String fileName)
            throws IOException {
        File targetFile = null;

        if (inputStream != null) {
            int read;
            byte[] buffer = new byte[8 * 1024];
            //自己定义拷贝文件路径
            checkFileCacheFolder();
            targetFile = new File(URI_FILE, fileName);
            if (targetFile.exists()) {
                targetFile.delete();
            }
            OutputStream outputStream = new FileOutputStream(targetFile);

            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetFile;
    }

}
